package cn.gailvlun.gll.chatlib.db

import cn.gailvlun.gll.chatlib.bean.BlockedRoom
import cn.gailvlun.gll.chatlib.bean.CrossMessage
import cn.gailvlun.gll.chatlib.bean.SystemNotification
import cn.gailvlun.gll.chatlib.message.Message
import cn.gailvlun.gll.chatlib.message.MessageStatus
import cn.gailvlun.gll.db.NetMigration
import cn.gailvlun.gll.db.NetModule
import cn.gailvlun.gll.net.apartment.room.Room
import cn.gailvlun.gll.net.base.friend.FriendNotification
import cn.gailvlun.gll.net.cross.CrossQuestionInfo
import cn.gailvlun.gll.net.cross.CrossResult
import cn.gailvlun.gll.net.cross.CrossRoomInfo
import cn.gailvlun.gll.util.LogUtil
import cn.gailvlun.gll.util.ProfileUtil
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.RealmObject
import io.realm.Sort


object ChatDB2 {

    
    private var realmConfiguration: RealmConfiguration? = null

    fun setRealm() {
        val userId = ProfileUtil.getUserId()
        LogUtil.e("setRealm()")
        realmConfiguration = RealmConfiguration.Builder()
                .name("chat-$userId.realm")
                .modules(ChatLibModule(), NetModule())
                .schemaVersion(5)
                .migration(ChatLibMigration())
                .build()
    }

    fun getConfiguration(): RealmConfiguration {
        LogUtil.e("realmConfiguration is $realmConfiguration")
        if (realmConfiguration == null) {
            val userId = ProfileUtil.getUserId()
            realmConfiguration = RealmConfiguration.Builder()
                    .name("chat-$userId.realm")
                    .modules(ChatLibModule(), NetModule())
                    .schemaVersion(5)
                    .migration(ChatLibMigration())
                    .build()
        }
        return realmConfiguration!!
    }

    fun saveMsg(msg: Message): Boolean {
        var realm = Realm.getInstance(realmConfiguration)
        val isSaved = realm.where(Message::class.java)
                .equalTo("id", msg.id)
                .findFirst() != null
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(msg)
        }
        realm.close()
        return isSaved
    }

    fun saveCrossMsg(msg: CrossMessage): Boolean {
        var realm = Realm.getInstance(realmConfiguration)
        val isSaved = realm.where(CrossMessage::class.java)
                .equalTo("id", msg.id)
                .findFirst() != null
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(msg)
        }
        realm.close()
        return isSaved
    }

    fun saveNoti(noti: SystemNotification) {
        var realm = Realm.getInstance(realmConfiguration)
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(noti)
        }
        realm.close()
    }

    fun saveFriendNoti(friendNoti: FriendNotification) {
        var realm = Realm.getInstance(realmConfiguration)
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(friendNoti)
        }
        realm.close()
    }

    fun saveRoom(room: Room) {
        var realm = Realm.getInstance(realmConfiguration)
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(room)
        }
        realm.close()
    }

    fun save(obj: RealmObject) {
        var realm = Realm.getInstance(realmConfiguration)
        realm!!.executeTransaction { realm ->
            realm.insertOrUpdate(obj)
        }
        realm.close()
    }

    fun deleteAllRoomMessage(roomId: Int) {
        var realm = Realm.getInstance(realmConfiguration)
        realm!!.executeTransaction { realm ->
            realm.where(Message::class.java)
                    .equalTo("dialogId", "room:" + roomId)
                    .findAll()
                    .deleteAllFromRealm()
        }
        realm.close()
    }

    fun searchRoomById(roomId: Int): Room? {
        var realm = Realm.getInstance(realmConfiguration)
        var room = realm.copyFromRealm(realm.where(Room::class.java)
                .equalTo("id", roomId)
                .findFirst())
        realm.close()
        return room
    }

    fun getCrossRoomInfo(): CrossRoomInfo? {
        var realm = Realm.getInstance(realmConfiguration)
        var crossRoomInfo = realm.copyFromRealm(realm.where(CrossRoomInfo::class.java)
                .sort("id", Sort.DESCENDING)
                .findFirst())
        realm.close()
        return crossRoomInfo
    }

    fun logout() {
        realmConfiguration = RealmConfiguration.Builder()
                .name("chat-invalid.realm")
                .modules(ChatLibModule(), NetModule())
                .schemaVersion(5)
                .migration(NetMigration())
                .build()
    }

    fun saveFirstRiddleAnswer(crossResult: CrossResult) {
        val realm = Realm.getInstance(ChatDB2.getConfiguration())

        realm.executeTransaction { realm ->
            val info = realm.where(CrossQuestionInfo::class.java)
                    .equalTo("id", crossResult.first.id)
                    .findFirst()
            info!!.otherAnswer = crossResult.first_answer
        }
        realm.close()
    }

    fun saveSecondRiddleAnswer(crossResult: CrossResult) {
        val realm = Realm.getInstance(ChatDB2.getConfiguration())

        realm.executeTransaction { realm ->
            val info = realm.where(CrossQuestionInfo::class.java)
                    .equalTo("id", crossResult.second.id)
                    .findFirst()
            info!!.otherAnswer = crossResult.second_answer
        }
        realm.close()
    }

    fun block(roomId: Int) {
        val realm = Realm.getInstance(ChatDB2.getConfiguration())

        realm.executeTransaction {
            it.insertOrUpdate(BlockedRoom().apply {
                this.roomId = roomId
            })
        }
        realm.close()
    }

    fun saveAsSuccess(msgId: String): String? {
        val realm = Realm.getInstance(ChatDB2.getConfiguration())
        val msg = realm.where(Message::class.java)
                .equalTo("id", msgId)
                .findFirst()
        val dialogId = msg?.dialogId
        if (msg != null) {
            realm.executeTransaction {
                msg.messageStatus = MessageStatus.SUCCESS
                it.insertOrUpdate(msg)
            }
        }

        realm.close()
        return dialogId
    }

    fun unblock(roomId: Int) {
        val realm = Realm.getInstance(ChatDB2.getConfiguration())

        var blockedRoom = realm.where(BlockedRoom::class.java)
                .equalTo("roomId", roomId)
                .findFirst()

        if (blockedRoom != null) {
            realm.executeTransaction {
                blockedRoom.deleteFromRealm()
            }
        }
        realm.close()
    }
}